package com.ruoyi.web.controller.check;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mchange.v1.util.ListUtils;
import com.ruoyi.check.domain.*;
import com.ruoyi.check.service.IECheckListFormItemService;
import com.ruoyi.check.service.IECheckListFormNameService;
import com.ruoyi.check.service.ISequenceService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.sun.jna.platform.win32.WinDef;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.check.service.IECheckListFormValueService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 检点记录Controller
 *
 * @author hugh.sun
 * @date 2023-03-23
 */

@Api(tags = "value")
@RestController
@RequestMapping("/check/value")
public class ECheckListFormValueController extends BaseController
{
    @Autowired
    private IECheckListFormValueService eCheckListFormValueService;
    @Autowired
    private IECheckListFormItemService ieCheckListFormItemService;
    @Autowired
    private IECheckListFormNameService eCheckListFormNameService;

    @Autowired
    private ISequenceService sequenceService;

    /**
     * 查询检点记录列表
     */
    @ApiOperation("保存答案")
    @PostMapping("/answer")
    public String answer(@RequestBody ECheckVOT o){

        try{

        String name = o.getName();

        List<ValueVo> data = o.getData();


        //根据表名去查id
        ECheckListFormName tbaleName = eCheckListFormNameService.findTbaleName(name);

        //表id
        Long id = tbaleName.getId();
        Long max;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String username = loginUser.getUsername();


            try {
                //插入序列号//表名序列号 查当前表名的最高序列号 一张表没点检一次对应一个序列
                Sequence sequence = new Sequence();
                sequence.setTablename(name);
                List<Long> longs = new ArrayList<>();
                List<Sequence> sequences = sequenceService.selectSequenceList(sequence);
                sequences.forEach(i -> {
                    Long os = i.getId();
                    longs.add(os);
                });
               max = Collections.max(longs);
            }catch (Exception e){
                 max = 0L;
            }
             max = max + 1;
            Long finalMax = max;
            Sequence sequence2 = new Sequence();
            sequence2.setCtime(new Date());
            sequence2.setTablename(name);
            sequence2.setOnlys(String.valueOf(finalMax));
            sequenceService.insertSequence(sequence2);
            data.forEach(i->{
            int tihao = i.getTihao();
            ECheckListFormValue eCheckListFormValue = new ECheckListFormValue();
            eCheckListFormValue.setFormId(id);
            eCheckListFormValue.setCreateUser(username);
            eCheckListFormValue.seturl(i.getValue());
            eCheckListFormValue.setItemId(Long.valueOf(tihao));
            //这个得去表中查查到对应的表名的最好
            eCheckListFormValue.setSerialId(String.valueOf(finalMax));
            String value = i.getValue();
            eCheckListFormValueService.insertECheckListFormValue(eCheckListFormValue);
        });
        }catch (Exception e){
            System.out.println(e.getMessage());
            //失败零成功一
            return "0";
        }
        return  "1";

    }




    @PreAuthorize("@ss.hasPermi('check:value:list')")
    @GetMapping("/list")
    public TableDataInfo list(ECheckListFormValue eCheckListFormValue)
    {
        startPage();
        List<ECheckListFormValue> list = eCheckListFormValueService.selectECheckListFormValueList(eCheckListFormValue);
        return getDataTable(list);

    }
    @GetMapping("/host")
    public String host()
    {
        int localPort = 0;
        String hostname = null;
        try {
            InetAddress localHost = InetAddress.getLocalHost();
             hostname = localHost.getHostName();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        try {
            ServerSocket serverSocket = new ServerSocket(0); // 绑定一个随机端口
             localPort = serverSocket.getLocalPort();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return hostname+localPort;
    }

    /**
     * 导出检点记录列表
     */
    @PreAuthorize("@ss.hasPermi('check:value:export')")
    @Log(title = "检点记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ECheckListFormValue eCheckListFormValue)
    {
        List<ECheckListFormValue> list = eCheckListFormValueService.selectECheckListFormValueList(eCheckListFormValue);
        ExcelUtil<ECheckListFormValue> util = new ExcelUtil<ECheckListFormValue>(ECheckListFormValue.class);
        util.exportExcel(response, list, "检点记录数据");
    }

    /**
     * 获取检点记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('check:value:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(eCheckListFormValueService.selectECheckListFormValueById(id));
    }

    /**
     * 新增检点记录
     */
    @PreAuthorize("@ss.hasPermi('check:value:add')")
    @Log(title = "检点记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ECheckListFormValue eCheckListFormValue)
    {
        return toAjax(eCheckListFormValueService.insertECheckListFormValue(eCheckListFormValue));
    }

    /**
     * 修改检点记录
     */
    @PreAuthorize("@ss.hasPermi('check:value:edit')")
    @Log(title = "检点记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ECheckListFormValue eCheckListFormValue)
    {
        return toAjax(eCheckListFormValueService.updateECheckListFormValue(eCheckListFormValue));
    }

    /**
     * 删除检点记录
     */
    @PreAuthorize("@ss.hasPermi('check:value:remove')")
    @Log(title = "检点记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(eCheckListFormValueService.deleteECheckListFormValueByIds(ids));
    }
    @GetMapping( "/hasakei")
    public List<HangAndLie> hasakei(ShouYeVo shouYeVo)
    {
        //拿到表名题名
        try {
            int select1 = shouYeVo.getSelect1();
            int select2 = shouYeVo.getSelect2();
            ArrayList<HangAndLie> hangAndLies = new ArrayList<>();

            ECheckListFormValue eCheckListFormValue = new ECheckListFormValue();

            eCheckListFormValue.setId(Long.valueOf(select1));
            eCheckListFormValue.setItemId(Long.valueOf(select2));
            List<ECheckListFormValue> eCheckListFormValues = eCheckListFormValueService.selectECheckListFormValueList(eCheckListFormValue);
            eCheckListFormValues.forEach(i->{
                HangAndLie hangAndLie = new HangAndLie();

                /*
                * SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = sdf.format(date);
                * */

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date createTime = i.getCreateTime();
                String format = sdf.format(createTime);
                hangAndLie.setLie(Integer.valueOf(i.geturl()));
                hangAndLie.setHang(format);

                hangAndLies.add(hangAndLie);


            });






            return hangAndLies;
        }catch (Exception e){
            ArrayList<HangAndLie> hangAndLies = new ArrayList<>();
            HangAndLie hangAndLie = new HangAndLie();
            hangAndLie.setLie(1);
            hangAndLie.setHang("1");
            return hangAndLies;
        }
    }


}
